import React, { Component } from 'react'
import { BASE_URL } from '../../utils/axios'
import styles from'./index.module.scss'
import { withRouter, Link } from 'react-router-dom'
import PropTypes from 'prop-types'
import NoHouse from '../NoHouse'

class HouseItem extends Component {

  static propTypes = {
    housesList: PropTypes.array.isRequired
  }

  state = {
    housesList: []
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const { housesList } = nextProps;
    // 当传入的 housesList 发生变化的时候，更新state
    if (housesList !== prevState.housesList) {
        return {
          housesList
        };
    }
    // 否则，对于state不进行任何操作
    return null;
  }

  render() {
    const { housesList } = this.state;
    return housesList.length > 0 ? (
      <div className={styles.houseItems}>
        {
          housesList.map(item => (
            <div className={styles.house} key={item.houseCode} onClick={()=> this.props.history.push('/detail/' + item.houseCode)}>
              <div className={styles.imgWrap}>
                <img src={BASE_URL + item.houseImg} alt="" className={styles.img} />
              </div>
              <div className={styles.content}>
                <h3 className={styles.title}>
                  {item.title}
                </h3>
                <div className={styles.desc}>{item.desc}</div>
                <div>
                  {
                    item.tags.map((tag, index) => <span className={[styles.tag, styles['tag' + (index + 1)]].join(' ')} key={tag}>{tag}</span>)
                  }
                </div>
                <div className={styles.price}>
                  <span className={styles.priceNum}>{item.price}</span>元/月
                </div>
              </div>
            </div>
          ))
        }
      </div>
    ) : <NoHouse>你还没有房源，<Link style={{color: 'rgb(98, 201, 173)'}} to="/rent/add">去发布房源</Link>吧~</NoHouse>
  }
}
export default withRouter(HouseItem);